package com.eg366.selfFrame.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;

import com.eg366.selfFrame.advisor.SelfAdvisor;
import com.eg366.selfFrame.annotation.DoAfter;
import com.eg366.selfFrame.annotation.DoBefore;

/**
 * jdk动态代理处理handler
 * 
 * @author eg366
 * 
 */
public class JdkDynamicAopProxy implements AopProxy, InvocationHandler {

	private Object target;
	private Class<?>[] interfaces;
	private Map<String, SelfAdvisor> aopAdvisorMap;

	public JdkDynamicAopProxy(AopSupport aopSupport) {
		target = aopSupport.getTarget();
		interfaces = target.getClass().getInterfaces();
		aopAdvisorMap = aopSupport.getAopAdvisorMap();
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		/* 判断方法上是否有aop注解 */
		DoBefore beforeAnno = target.getClass().getDeclaredMethod(method.getName(), method.getParameterTypes())
				.getAnnotation(DoBefore.class);
		if (beforeAnno != null) {
			String[] aspectIds = beforeAnno.aspectId();
			for (String aspectId : aspectIds) {
				aopAdvisorMap.get(aspectId).doProcess();
			}
		}
		Object result = method.invoke(target, args);
		DoAfter afterAnno = target.getClass().getDeclaredMethod(method.getName(), method.getParameterTypes())
				.getAnnotation(DoAfter.class);
		if (afterAnno != null) {
			String[] aspectIds = afterAnno.aspectId();
			for (String aspectId : aspectIds) {
				aopAdvisorMap.get(aspectId).doProcess();
			}
		}
		return result;
	}

	@Override
	public Object getProxy(ClassLoader classLoader) {
		return Proxy.newProxyInstance(classLoader, interfaces, this);
	}

}
